import { useState, useEffect, FC } from 'react'
import { Input, Popover } from 'antd'
import { ClockCircleOutlined } from '@ant-design/icons'
import F from 'react-free-scrollbar'
import moment, { Moment } from 'moment'
import style from './index.module.less'

const FreeScrollBar = F as unknown as FC<any>

function formatDoubleNum (n = 0) {
  return n >= 10 ? String(n) : `0${n}`
}

function initHourAndMinute (
  value: Moment | undefined,
  setSelectedValue: (v: string) => void,
  setHour: (v: number) => void,
  setMinute: (v: number) => void
) {
  if (value instanceof moment) {
    setSelectedValue(value.format('HH:mm'))
    setHour(value.hour())
    setMinute(value.minute())
  } else if (!value) {
    setSelectedValue('')
    setHour(0)
    setMinute(0)
  }
}

// 初始化小时列表
function initHourList (disabledHours: () => number[], setHourList: (v: number[]) => void) {
  const d = disabledHours()
  const list = []
  for (let i = 0; i < 24; i++) {
    if (d.indexOf(i) === -1) {
      list.push(i)
    }
  }
  setHourList(list)
}

// 初始化分钟列表
function initMinuteList (disabledMinutes: () => number[], setMinuteList: (v: number[]) => void) {
  const d = disabledMinutes()
  const list = []
  for (let i = 0; i < 60; i++) {
    if (d.indexOf(i) === -1) {
      list.push(i)
    }
  }
  setMinuteList(list)
}

function renderHourList (list: number[], hour: number, selectHour: (v: number) => void) {
  if (list.length > 10) {
    return (
      <FreeScrollBar className='mock' style={{ height: '240px' }}>
        <div className={style['more-list']}>
          {list.map(l => {
            const cn = [style.dd]
            if (hour === l) {
              cn.push(style.active)
            }
            return <div className={cn.join(' ')} key={l} onClick={() => selectHour(l)}>{formatDoubleNum(l)}</div>
          })}
        </div>
      </FreeScrollBar>
    )
  }
  return list.map(l => {
    const cn = [style.dd]
    if (hour === l) {
      cn.push(style.active)
    }
    return <div className={cn.join(' ')} key={l} onClick={() => selectHour(l)}>{formatDoubleNum(l)}</div>
  })
}

function renderMinuteList (list: number[], minute: number, selectMinute: (v: number) => void) {
  if (list.length > 10) {
    return (
      <FreeScrollBar className='mock' style={{ height: '240px' }}>
        <div className={style['more-list']}>
          {list.map(l => {
            const cn = [style.dd]
            if (minute === l) {
              cn.push(style.active)
            }
            return <div className={cn.join(' ')} key={l} onClick={() => selectMinute(l)}>{formatDoubleNum(l)}</div>
          })}
        </div>
      </FreeScrollBar>
    )
  }
  return list.map(l => {
    const cn = [style.dd]
    if (minute === l) {
      cn.push(style.active)
    }
    return <div className={cn.join(' ')} key={l} onClick={() => selectMinute(l)}>{formatDoubleNum(l)}</div>
  })
}

interface Props {
  value?: Moment
  disabledHours?: () => number[]
  disabledMinutes?: () => number[]
  onChange?: (v: Moment) => void
  placeholder?: string
}

function Main ({ value, onChange = () => {}, disabledHours = () => [], disabledMinutes = () => [], placeholder = '请选择时间' }: Props) {
  const [hourList, setHourList] = useState<number[]>([])
  const [minuteList, setMinuteList] = useState<number[]>([])
  const [hour, setHour] = useState(0)
  const [minute, setMinute] = useState(0)
  const [selectedValue, setSelectedValue] = useState('')
  useEffect(() => {
    initHourList(disabledHours, setHourList)
    initMinuteList(disabledMinutes, setMinuteList)
  }, [])
  useEffect(() => {
    initHourAndMinute(value, setSelectedValue, setHour, setMinute)
  }, [value])
  useEffect(() => {
    const value = moment()
    value.hour(hour)
    value.minute(minute)
    setSelectedValue(`${formatDoubleNum(hour)}:${formatDoubleNum(minute)}`)
    onChange(value)
  }, [hour, minute])
  return (
    <Popover content={(
      <div className={style.container}>
        <div className={style.list}>
          <div className={hourList.length > 10 ? [style.dt, style['more-dt']].join(' ') : style.dt}>小时</div>
          {renderHourList(hourList, hour, setHour)}
        </div>
        <div className={style.list}>
          <div className={minuteList.length > 10 ? [style.dt, style['more-dt']].join(' ') : style.dt}>分钟</div>
          {renderMinuteList(minuteList, minute, setMinute)}
        </div>
      </div>
    )} title={false} trigger={['click']} placement='bottom'>
      <Input placeholder={placeholder} value={selectedValue} className={style.input} suffix={<ClockCircleOutlined />} readOnly />
    </Popover>
  )
}

export default Main
